package com.bjesc_b2c.app.appraiset.mvp.view.fragment;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;

import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.RequestAndResultCode;
import com.bjesc_b2c.app.appraiset.base.BaseCarSourcePhotoFragment;
import com.bjesc_b2c.app.appraiset.bean.TakePhotoBean;
import com.bjesc_b2c.app.appraiset.camera.TakePhoto;
import com.bjesc_b2c.app.appraiset.utils.TimeListUilts;
import com.bjesc_b2c.app.appraiset.widget.popupwindow.SelectPhotoPop;
import com.example.codeutils.utils.FileUtils;
import com.example.codeutils.utils.SDCardUtils;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.rxretrofit_build.CarPhotoID;
import com.rxretrofit_build.model.RxBusBean;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.io.File;
import java.util.List;

import app.pinggushi.bjesc.com.baserecyclerview.adapter.MultiItemTypeAdapter;
import master_bean.CarSourcePhotoBean;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static android.app.Activity.RESULT_OK;
import static com.bjesc_b2c.app.appraiset.utils.BitmapUtil.copyFile;


/**
 * Created by lenovo on 2017/2/24.
 */

public class CarEngineFragment extends BaseCarSourcePhotoFragment implements MultiItemTypeAdapter.OnItemClickListener {
    @Override
    protected String getSourceID() {
        return CarPhotoID.ORNAMENTSID;
    }
    @Override
    protected void getSourceList() {
        photoBeanList = TimeListUilts.getOrnamentsPhotoList();
    }

    @Override
    public void initView() {
        super.initView();
        photoAdapter.setOnItemClickListener(this);
        photoPop = new SelectPhotoPop(getActivity(), popListener);
    }

    @Override
    public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
        currentIndex = position;
        if (TextUtils.isEmpty(photoBeanList.get(position).getPhoto())) {
            //打开popupWindow
            photoPop.showAtLocation(getActivity().findViewById(R.id.llty_root), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        } else {
            //跳转大图
            bigPhotoIntent.putExtra("photoUrl", photoBeanList.get(position).getPhoto());
            bigPhotoIntent.putExtra("from", "CarEngineFragment");
            bigPhotoIntent.putExtra("Title",photoBeanList.get(position).getPhotoName());
            if(fileList!=null && fileList.size() < position){
                bigPhotoIntent.putExtra("fileName", TimeListUilts.subUrl(photoBeanList.get(position).getPhoto()));
            }else{
                bigPhotoIntent.putExtra("fileName",photoBeanList.get(position).getPhoto());
            }
            bigPhotoIntent.putExtra("classId", CarPhotoID.ORNAMENTSID);
            bigPhotoIntent.putExtra("sourceId",photoBeanList.get(position).getId());
            startIntent(bigPhotoIntent, RequestAndResultCode.CARENGINEFRAGMENT_TO_BIGCARSOURCEPHOTOACTIVITY_REQUEST);
        }
    }

    @Override
    public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder,int position) {
        return false;
    }

    private View.OnClickListener popListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.rlty_select_camera:     //选择相机
//                    GralleryFinalUtils.openCamera(gralleryCallBack);
                    Intent intent = new Intent(getActivity(), TakePhoto.class);
                    intent.putExtra("currentIndex",currentIndex);
                    intent.putExtra("CarPhotoID", CarPhotoID.ORNAMENTSID);
                    startActivityForResult(intent,1);
                    break;
                case R.id.rlty_select_album:    //选择相册
//                    RxGralleryFinalUtils.openRadioImage(getActivity(), rxGalleryCallBack);
                    Matisse.from(CarEngineFragment.this)
                            .choose(MimeType.ofImage())
                            .countable(true)
                            .maxSelectable(1)
//                                        .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                            .gridExpectedSize(
                                    getResources().getDimensionPixelSize(R.dimen.dimen_120))
                            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                            .thumbnailScale(0.85f)
                            .imageEngine(new GlideEngine())
                            .forResult(REQUEST_CODE_CHOOSE);
                    break;
            }
            if (photoPop.isShowing()) {
                photoPop.dismiss();
            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Logger.d("onActivityResult");
//        showToast("onActivityResult");
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == TakePhoto.BACK_PHOTO_SUCCEED){
            List<TakePhotoBean> listData = (List<TakePhotoBean>)data.getSerializableExtra("photoBeanList");
            if(listData != null){
                for (int i = 0; i < listData.size(); i ++ ){
                    refreshImage(listData.get(i).getUrl(),listData.get(i).getIndex());
                }
            }
        }
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            List<Uri> mSelected = Matisse.obtainResult(data);
            Uri selectedImage = mSelected.get(0);
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            Cursor c = getActivity().getContentResolver().query(selectedImage, filePathColumns, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePathColumns[0]);
            String imagePath = c.getString(columnIndex);
            Logger.d("imagePath=="+imagePath);
            final File file1Path = new File(imagePath);
            Luban.with(getActivity())
                    .load(file1Path)                 //传人要压缩的图片//设定压缩档次，默认三挡
                    .setCompressListener(new OnCompressListener() { //设置回调
                        @Override
                        public void onStart() {
                            // TODO 压缩开始前调用，可以在方法内启动 loading UI
                            Logger.d("压缩");
                        }
                        @Override
                        public void onSuccess(File file) {
                            Logger.d("压缩完成++"+file.getAbsolutePath());
                            copyFile(file,file1Path,true);
                            // TODO 压缩成功后调用，返回压缩后的图片文件

                        }

                        @Override
                        public void onError(Throwable e) {
                            // TODO 当压缩过去出现问题时调用
                        }
                    }).launch();    //启动压缩

            refreshImage(imagePath, currentIndex);
            c.close();
        }
    }


    /**
     * 保存图片
     *
     * @param rxBusBean
     */
    @Override
    protected void doOnNext(RxBusBean rxBusBean) {
        super.doOnNext(rxBusBean);
        if (rxBusBean.getRequestMark().equals(CarEngineFragment.class.getName())) {
            Logger.d(rxBusBean.getRequestMark().toString());
            upImgToALiYun();
            persnter.savePhoto(CarPhotoID.ORNAMENTSID, CarPhotoID.OrnamentsID.ornamentsOther, photoBeanList);
        } else if (rxBusBean.getRequestMark().equals("" + RequestAndResultCode.BIGCARSOURCEPHOTOACTIVITY_BACK_CARENGINEFRAGMENT_RESULT)) {
            if (TextUtils.isEmpty(photoBeanList.get(currentIndex).getPhotoName())) {
                photoBeanList.remove(currentIndex);
            } else {
                photoBeanList.set(currentIndex, new CarSourcePhotoBean(photoBeanList.get(currentIndex).getId(), "", photoBeanList.get(currentIndex).getPhotoName()));
            }
            photoAdapter.refresh(photoBeanList);
            FileUtils.writeFileFromString(SDCardUtils.getDataPath()+carId + File.separator + CarPhotoID.IMAGE_FILE_NAME + getSourceID()+".txt",new Gson().toJson(photoBeanList),false);
        }
    }


}
